const { Role, Permission, User, SystemLog } = require('../models');
const { AppError } = require('../middlewares/errorHandler');
const { logger } = require('../utils/logger');

class PermissionController {
  // 获取所有权限
  async getPermissions(ctx) {
    const permissions = await Permission.findAll();
    ctx.body = {
      status: 'success',
      data: {
        permissions
      }
    };
  }

  // 获取单个权限
  async getPermission(ctx) {
    const { id } = ctx.params;
    const permission = await Permission.findByPk(id);

    if (!permission) {
      throw new AppError(404, '权限不存在');
    }

    ctx.body = {
      status: 'success',
      data: {
        permission
      }
    };
  }

  // 创建权限
  async createPermission(ctx) {
    const { code, name, description } = ctx.request.body;

    // 检查权限代码是否已存在
    const existingPermission = await Permission.findOne({
      where: { code }
    });

    if (existingPermission) {
      throw new AppError(400, '权限代码已存在');
    }

    const permission = await Permission.create({
      code,
      name,
      description
    });

    // 记录操作日志
    await SystemLog.create({
      action: 'create_permission',
      operator: ctx.state.user.id,
      target_type: 'permission',
      target_id: permission.id,
      details: { permission }
    });

    ctx.body = {
      status: 'success',
      data: {
        permission
      }
    };
  }

  // 更新权限
  async updatePermission(ctx) {
    const { id } = ctx.params;
    const updateData = ctx.request.body;

    const permission = await Permission.findByPk(id);
    if (!permission) {
      throw new AppError(404, '权限不存在');
    }

    // 如果更新code，检查是否与其他权限冲突
    if (updateData.code && updateData.code !== permission.code) {
      const existingPermission = await Permission.findOne({
        where: { code: updateData.code }
      });

      if (existingPermission) {
        throw new AppError(400, '权限代码已存在');
      }
    }

    await permission.update(updateData);

    // 记录操作日志
    await SystemLog.create({
      action: 'update_permission',
      operator: ctx.state.user.id,
      target_type: 'permission',
      target_id: permission.id,
      details: { before: permission, after: updateData }
    });

    ctx.body = {
      status: 'success',
      data: {
        permission
      }
    };
  }

  // 删除权限
  async deletePermission(ctx) {
    const { id } = ctx.params;
    const permission = await Permission.findByPk(id);

    if (!permission) {
      throw new AppError(404, '权限不存在');
    }

    // 检查是否有角色在使用此权限
    const roles = await Role.findAll({
      include: [{
        model: Permission,
        where: { id }
      }]
    });

    if (roles.length > 0) {
      throw new AppError(400, '该权限正在被角色使用，无法删除');
    }

    await permission.destroy();

    // 记录操作日志
    await SystemLog.create({
      action: 'delete_permission',
      operator: ctx.state.user.id,
      target_type: 'permission',
      target_id: permission.id,
      details: { permission }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 创建角色
  async createRole(ctx) {
    const { name, description, permissions } = ctx.request.body;

    // 检查角色名是否已存在
    const existingRole = await Role.findOne({ where: { name } });
    if (existingRole) {
      throw new AppError(400, '角色名已存在');
    }

    // 创建角色
    const role = await Role.create({
      name,
      description
    });

    // 如果提供了权限列表，添加权限
    if (permissions && permissions.length > 0) {
      const permissionRecords = await Permission.findAll({
        where: { code: permissions }
      });
      await role.setPermissions(permissionRecords);
    }

    // 记录操作日志
    await SystemLog.create({
      action: 'create_role',
      operator: ctx.state.user.id,
      target_type: 'role',
      target_id: role.id,
      details: { role, permissions }
    });

    ctx.body = {
      status: 'success',
      data: {
        role
      }
    };
  }

  // 更新角色
  async updateRole(ctx) {
    const { id } = ctx.params;
    const { name, description, permissions } = ctx.request.body;

    const role = await Role.findByPk(id);
    if (!role) {
      throw new AppError(404, '角色不存在');
    }

    // 如果更新名称，检查是否与其他角色冲突
    if (name && name !== role.name) {
      const existingRole = await Role.findOne({ where: { name } });
      if (existingRole) {
        throw new AppError(400, '角色名已存在');
      }
    }

    // 更新角色基本信息
    await role.update({ name, description });

    // 如果提供了权限列表，更新权限
    if (permissions) {
      const permissionRecords = await Permission.findAll({
        where: { code: permissions }
      });
      await role.setPermissions(permissionRecords);
    }

    // 记录操作日志
    await SystemLog.create({
      action: 'update_role',
      operator: ctx.state.user.id,
      target_type: 'role',
      target_id: role.id,
      details: { before: role, after: { name, description, permissions } }
    });

    ctx.body = {
      status: 'success',
      data: {
        role
      }
    };
  }

  // 删除角色
  async deleteRole(ctx) {
    const { id } = ctx.params;
    const role = await Role.findByPk(id);

    if (!role) {
      throw new AppError(404, '角色不存在');
    }

    // 检查是否有用户在使用此角色
    const users = await User.findAll({
      include: [{
        model: Role,
        where: { id }
      }]
    });

    if (users.length > 0) {
      throw new AppError(400, '该角色正在被用户使用，无法删除');
    }

    await role.destroy();

    // 记录操作日志
    await SystemLog.create({
      action: 'delete_role',
      operator: ctx.state.user.id,
      target_type: 'role',
      target_id: role.id,
      details: { role }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 获取所有角色
  async getRoles(ctx) {
    const roles = await Role.findAll({
      include: [Permission]
    });

    ctx.body = {
      status: 'success',
      data: {
        roles
      }
    };
  }

  // 分配角色给用户
  async assignRoleToUser(ctx) {
    const { userId, roleId } = ctx.request.body;

    const user = await User.findByPk(userId);
    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    const role = await Role.findByPk(roleId);
    if (!role) {
      throw new AppError(404, '角色不存在');
    }

    await user.addRole(role);

    // 记录操作日志
    await SystemLog.create({
      action: 'assign_role',
      operator: ctx.state.user.id,
      target_type: 'user',
      target_id: userId,
      details: { userId, roleId }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 从用户移除角色
  async removeRoleFromUser(ctx) {
    const { userId, roleId } = ctx.request.body;

    const user = await User.findByPk(userId);
    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    const role = await Role.findByPk(roleId);
    if (!role) {
      throw new AppError(404, '角色不存在');
    }

    await user.removeRole(role);

    // 记录操作日志
    await SystemLog.create({
      action: 'remove_role',
      operator: ctx.state.user.id,
      target_type: 'user',
      target_id: userId,
      details: { userId, roleId }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 获取用户权限
  async getUserPermissions(ctx) {
    const { id } = ctx.params;
    const user = await User.findByPk(id, {
      include: [{
        model: Role,
        include: [Permission]
      }]
    });

    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    // 收集用户所有角色的权限
    const permissions = new Set();
    user.Roles.forEach(role => {
      role.Permissions.forEach(permission => {
        permissions.add(permission.code);
      });
    });

    ctx.body = {
      status: 'success',
      data: {
        permissions: Array.from(permissions)
      }
    };
  }
}

module.exports = new PermissionController(); 